Components.utils.import("resource://lucidity/lucidapi.jsm");
Components.utils.import("resource://gre/modules/JSON.jsm");
(function()
{
    function $(id, doc)
    {
        if (doc)
            return doc.getElementById(id);
        else
            return document.getElementById(id);
    }

    /* find a select in a frame */
    function getFrameSelection( selectable )
    {
        var selObj = ("getSelection" in selectable) ? selectable.getSelection() : null;
        if (selObj && (selObj.toString() != ""))
        {
            return selObj;
        }
        else
        {
            var frames = selectable.frames;
            if (!frames)
                return null;
            for (var ii = 0; ii < frames.length; ++ii)
            {
                selObj = getFrameSelection(frames[ii]);
                if (selObj)
                {
                    return selObj;
                }
            }
        }
        return null;
    }

    /* Return actual selection. */
    function getActiveSelection()
    {
        try {
            var selObj = getFrameSelection(getBrowser().contentWindow);
            if (selObj)
            {
                return selObj.toString();
            }
            else
            {
                var focused = document.commandDispatcher.focusedElement;
                if (focused && focused.value)
                {
                    return focused.value.substring(focused.selectionStart, focused.selectionEnd);
                }
            }
        } catch (e) {
            lucidapi.warn(e);
        }
        return "";
    }

    /* Modify the selection. */
    function setActiveSelection( text, siginfo )
    {
        if (lucidapi.config.noInPlaceResults)
            return false;

        var focused = document.commandDispatcher.focusedElement;
        if (!focused)
            return false;

        var startPos = focused.selectionStart;
        var endPos = focused.selectionEnd;
        var origval = focused.value;

        if (origval.substring(startPos, endPos).length < 1)
            return false;

        focused.value = origval.substring(0, startPos) + text + origval.substring(endPos, origval.length);

        focused.selectionStart = startPos;
        focused.selectionEnd = startPos + text.length;

        if (siginfo != null)
        {
            lucidapi.promptAlert(lucidapi.formatSignatureResultMessage(siginfo));
        }
        return true;
    }

    this.lucidctx = new (lucidapi.CryptoOperator.extend(function(classref) { return {
        initialize: function()
        {
            classref.superClass.initialize.call(this,window);
        },
        getInvocationTarget: function()
        {
            return getActiveSelection();
        },
        handleInplaceResult: function( resultobj )
        {
            var stuff = resultobj.m_result;
            var sigdata = resultobj.m_siginfo;
            if (stuff)
            {
                return setActiveSelection(stuff, sigdata);
            }
            else if (sigdata)
            {
                lucidapi.promptAlert(lucidapi.formatSignatureResultMessage(sigdata));
                return true;
            }
            return false;
        },
        openFileInEditor: function()
        {
            try
            {
                var data = lucidapi.loadThingWithPicker(window);
                if (data == null)
                    return; // user cancelled;
                lucidapi.openEditorWindow(data);
            }
            catch (e)
            {
                lucidapi.promptError(e);
            }
        },
        openEditor: function()
        {
            lucidapi.openEditorWindow(getActiveSelection());
        }
    }}));

    var apiObserver = new (lucidapi.AbstractClass.extend(function(classref) { return {

            initialize: function()
            {
                classref.superClass.initialize.call(this);
            },

            register: function(){
                var observerService = lucidapi.getXpcomService("@mozilla.org/observer-service;1", "nsIObserverService");
                observerService.addObserver(this,"lucid-logmsg",false);
//                observerService.addObserver(this,"lucid-pcache",false);
            },

            unregister: function(){
                var observerService = lucidapi.getXpcomService("@mozilla.org/observer-service;1", "nsIObserverService");
                observerService.removeObserver(this,"lucid-logmsg");
//                observerService.removeObserver(this,"lucid-pcache");
            },

            observe: function(subject,topic,data){
                switch (topic) {
                    case "lucid-logmsg":
//                        addStuffToLog(JSON.fromString(data));
                        break;
                }
            }

    }}));

    window.addEventListener("load", function()
    {
        lucidapi.checkForUpgrade();
        apiObserver.register();
    }, false);

    window.addEventListener("unload", function() {
        apiObserver.unregister();
    }, false );

})();

